package cz.acies.data.dao;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;

import cz.acies.data.dao.AbstractDAO;
import cz.acies.data.persist.TreeNode;
import cz.acies.uniql.sql.SelectQuery;
import cz.acies.uniql.sql.element.UniQLOrderBy;

public abstract class MModelFolderDAO extends AbstractDAO
{

	public MModelFolderDAO() {}
	
	public List<TreeNode> createFolders(List<String> tables) {
		List<TreeNode> data = new ArrayList<TreeNode>();
		try {
			if (!tables.isEmpty()) {
				tableName = tables.get(0);
				Map<String, TreeNode> reg = new LinkedHashMap<String, TreeNode>();
				
				QueryRunner qr = new QueryRunner(ds());
				SelectQuery sql = new SelectQuery(dbmd())
				.addFrom("" + tableName)
				.add(new UniQLOrderBy("parentId"))
				.add(new UniQLOrderBy("priority"));
				
				List<Map<String, Object>> menuData = qr.query(sql.toSQLString(), new DefaultMapListHandler(new DefaultRowProcessor()));
				for (Map<String, Object> row : menuData) {
					String id = (String) row.get("id");
					String parentId = (String) row.get("parentId");
					String label = (String) row.get("label");
					
					TreeNode parent = reg.get(""+parentId); 
					TreeNode node = new TreeNode(id, label);
	
					if (parent != null) {
						node.setAttribute("selectable", true);
						parent.addChild(node);
					} else {
						data.add(node);
					}
					reg.put(id, node);
				}
			}
		} catch (Exception exc) {
			exc.printStackTrace();
		}
		return data;
	}
}
